from rest_framework import viewsets


from MirrorCore.models.Content import Essay
from MirrorCore.permissions.permisssion import IsStaffOrReadOnly
from MirrorCore.serializers.BadgeSeriralizer import EssayBadgeSerializer
from MirrorCore.serializers.EssaySerializer import EssaySerializer
from MirrorCore.views.utils.BadgeList import update_badge_list
from rest_framework.decorators import action

class EssayViewSet(viewsets.ModelViewSet):
    queryset = Essay.objects.all().order_by('-create_time')
    serializer_class = EssaySerializer

    permission_classes = [IsStaffOrReadOnly]

    def get_queryset(self):
        if self.request.user.is_staff:
            return Essay.objects.all().order_by("-id")
        return Essay.objects.filter(is_active=True).order_by("-id")

    def get_serializer_class(self):
        return super().get_serializer_class()

    def update(self, request, *args, **kwargs):
        data = request.data
        """ 单独处理 badges 的修改 """

        update_badge_list(model=self.serializer_class.Meta.model.badges.field.model
                          , name='essay', pk=kwargs['pk'],
                          serializer=EssayBadgeSerializer,
                          data=data.get("badges")
                          )

        return super().update(request, *args, **kwargs)


    def destroy(self, request, *args, **kwargs):

        """ 单独处理 badges 的修改 传入空数组达到删除目的 """
        update_badge_list(model=self.serializer_class.Meta.model.badges.field.model
                          , name='essay', pk=kwargs['pk'],
                          serializer=EssayBadgeSerializer,
                          data=[]
                          )

        return super().destroy(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)

    def create(self, request, *args, **kwargs):

        """
            Todo 该函数未返回一同创建的badges
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        print(request.data)
        data = super().create(request, *args, **kwargs)

        print(data.data['id'])

        """ 单独处理 badges 的修改 """
        update_badge_list(model=self.serializer_class.Meta.model.badges.field.model
                          , name='essay', pk=data.data['id'],
                          serializer=EssayBadgeSerializer,
                          data=request.data.get("badges")
                          )
        return data




